/**
 * yeahmobi.com Inc.
 * Copyright © 2014 YeahMobi | All Rights Reserved.
 */

package com.ndp.fb.rdb.mongo.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.*;
import com.ndp.fb.constant.MongoConstants;
import com.ndp.fb.mongo.api.AccountAdImageMongoService;
import com.ndp.fb.mongo.api.IMongodbService;
import com.ndp.fb.mongo.model.AccountAdImageMongo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author giser.yang
 * @Title: AccountAdImageMongoServiceImpl.java
 * @Copyright: Copyright © 2015
 * @Description:
 * @Company: yeahmobi
 * @Created on 上午10:46:34
 */
@Service
public class AccountAdImageMongoServiceImpl implements AccountAdImageMongoService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private DB mongoDBClient;

    @Autowired
    private IMongodbService mongodbService;

    /**
     * @param accountAdImageMongo
     * @discription
     * @author giser.yang
     * 创建时间 2015年7月17日 上午10:46:49
     * @see com.ndp.fb.mongo.api.AccountAdImageMongoService#saveAccountAdImage(com.ndp.fb.mongo.model.AccountAdImageMongo)
     */

    @Override
    public void saveAccountAdImage(AccountAdImageMongo accountAdImageMongo) {
        if (accountAdImageMongo == null) {
            logger.info("accountimage入库对象为空，退出入库操作");
            return;
        }
        try {
            DBCollection collection = mongoDBClient.getCollection(MongoConstants.TABLE_NAME_ACCOUNT_AD_IMAGE_LIB);
            DBObject query = new BasicDBObject();
            query.put("mongodbId", accountAdImageMongo.getId());
            DBObject update = (DBObject) com.mongodb.util.JSON.parse(JSONObject.toJSONString(accountAdImageMongo));
            collection.update(query, update, true, false);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("-----向mongoDB：" + MongoConstants.TABLE_NAME_ACCOUNT_AD_IMAGE_LIB + "集合插入数据完成");
    }

    /**
     * @param accountAdImageMongo
     * @discription
     * @author giser.yang
     * 创建时间 2015年7月17日 上午11:34:13
     * @see com.ndp.fb.mongo.api.AccountAdImageMongoService#batchSaveOrUpdateAccountAdImage(java.util.List)
     */

    @Override
    public void batchSaveOrUpdateAccountAdImage(
            List<AccountAdImageMongo> accountAdImageMongo) {
        if (CollectionUtils.isEmpty(accountAdImageMongo)) {
            logger.info("accountimage入库列表为空，退出入库操作");
            return;
        }
        try {
            mongodbService.batchSaveOrUpdateWithoutHistory(mongoDBClient, MongoConstants.TABLE_NAME_ACCOUNT_AD_IMAGE_LIB, JSONObject.toJSONString(accountAdImageMongo), new String[]{"mongodbId"}, false);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        logger.info("-----向mongoDB：" + MongoConstants.TABLE_NAME_ACCOUNT_AD_IMAGE_LIB + "集合插入数据完成");
    }

    /**
     * @param md5isNull
     * @return
     * @discription
     * @author giser.yang
     * 创建时间 2015年7月17日 下午2:46:08
     * @see com.ndp.fb.mongo.api.AccountAdImageMongoService#getAccountAdImageMongosforMd5(boolean)
     */

    @Override
    public List<AccountAdImageMongo> getAccountAdImageMongosforMd5(
            boolean md5isNull) {
        return this.getAccountAdImageMongos(null, md5isNull);
    }

    /**
     * @param md5isNull
     * @return
     * @discription
     * @author giser.yang
     * 创建时间 2015年7月17日 下午2:46:08
     * @see com.ndp.fb.mongo.api.AccountAdImageMongoService#getAccountAdImageMongos(java.util.List, boolean)
     */

    @Override
    public List<AccountAdImageMongo> getAccountAdImageMongos(
            List<Long> accountIds, boolean md5isNull) {
        DBCollection conn = mongoDBClient.getCollection(MongoConstants.TABLE_NAME_ACCOUNT_AD_IMAGE_LIB);
        DBObject query = new BasicDBObject();
        if (!CollectionUtils.isEmpty(accountIds)) {
            query.put("accoundId", new BasicDBObject("$in", accountIds));
        }
        if (md5isNull) {
            query.put("md5", null);
            query.put("$or", new Object[]{new BasicDBObject("md5", null), new BasicDBObject("md5", "")});
        }
        DBCursor dbCursor = conn.find(query);
        List<AccountAdImageMongo> acAdImageMongos = null;
        if (dbCursor != null) {
            acAdImageMongos = new ArrayList<>();
            DBObject dbObject = null;
            while (dbCursor.hasNext()) {
                dbObject = dbCursor.next();
                acAdImageMongos.add(JSONObject.parseObject(JSON.toJSONString(dbObject), AccountAdImageMongo.class));
            }
        }
        return acAdImageMongos;
    }

    /**
     * @param mongodbId
     * @param localUrl
     * @param localUrl128
     * @param md5
     * @discription
     * @author giser.yang
     * 创建时间 2015年7月20日 下午2:05:06
     * @see com.ndp.fb.mongo.api.AccountAdImageMongoService#updateAccountAdImageUrl128MD5(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */

    @Override
    public void updateAccountAdImageUrl128MD5(String mongodbId,
                                              String localUrl, String localUrl128, String md5) {
        logger.info("-----更新accountimage" + mongodbId + "的md5");
        try {
            DBCollection collection = mongoDBClient.getCollection(MongoConstants.TABLE_NAME_ACCOUNT_AD_IMAGE_LIB);
            DBObject query = new BasicDBObject();
            query.put("mongodbId", mongodbId);
            DBObject o = new BasicDBObject();
            o.put("localUrl", localUrl);
            o.put("localUrl128", localUrl128);
            o.put("md5", md5);

            collection.update(query, new BasicDBObject("$set", o));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("-----更新accountimage" + mongodbId + "的md5完成");
    }

    /**
     * @param imageHash
     * @discription
     * @author giser.yang
     * 创建时间 2015年7月27日 下午1:15:15
     * @see com.ndp.fb.mongo.api.AccountAdImageMongoService#getMd5byImageHash(java.lang.String)
     */

    @Override
    public String getMd5byImageHash(String imageHash) {
        if (StringUtils.isEmpty(imageHash)) {
            return null;
        }
        DBCollection collection = mongoDBClient.getCollection(MongoConstants.TABLE_NAME_ACCOUNT_AD_IMAGE_LIB);
        DBObject query = new BasicDBObject();
        query.put("hash", imageHash);
        query.put("md5", new BasicDBObject("$ne", null));
        DBObject dbObject = collection.findOne(query);
        if (dbObject == null) {
            return null;
        }
        if (dbObject.get("md5") == null) {
            return null;
        }
        return dbObject.get("md5").toString();
    }

    @Override
    public String getImageHashbyMd5(String md5) {
        if (StringUtils.isEmpty(md5)) {
            return null;
        }
        DBCollection collection = mongoDBClient.getCollection(MongoConstants.TABLE_NAME_ACCOUNT_AD_IMAGE_LIB);
        DBObject query = new BasicDBObject();
        query.put("md5", md5);
        query.put("hash", new BasicDBObject("$ne", null));
        DBObject dbObject = collection.findOne(query);
        if (dbObject == null) {
            return null;
        }
        if (dbObject.get("hash") == null) {
            return null;
        }
        return dbObject.get("hash").toString();
    }

	@Override
	public AccountAdImageMongo getAccountAdImageMongobyImageHash(String imageHash) {
		if (StringUtils.isEmpty(imageHash)) {
            return null;
        }
        DBCollection collection = mongoDBClient.getCollection(MongoConstants.TABLE_NAME_ACCOUNT_AD_IMAGE_LIB);
        DBObject query = new BasicDBObject();
        query.put("hash", imageHash);
        DBObject dbObject = collection.findOne(query);
        if (dbObject == null) {
            return null;
        }
        return JSONObject.parseObject(JSONObject.toJSONString(dbObject), AccountAdImageMongo.class);
	}

}
